<?php

namespace App\Http\Controllers;

use App\Http\Requests\AddCartRequest;
use App\Models\CartItem;
use App\Models\ProductSku;
use App\Services\CartService;
use Illuminate\Http\Request;

class CartController extends Controller
{
    protected $cartService;

    //利用lavavel 自动解析功能注入cartService
    public function __construct(CartService $cartService)
    {
        $this->cartService = $cartService;
    }

    //购物车首页
    public function index(Request $request)
    {
      //  with(['productSku.product']) 方法用来预加载购物车里的商品和 SKU 信息。
        //。如果这里没有进行预加载而是在渲染模板时通过 $item->productSku->product 这种懒加载的方式，就会出现购物车中的每一项都要执行多次商品信息的 SQL 查询，导致单个页面执行的 SQL 数量过多，加载性能差的问题
        //$cartItems = $request->user()->cartItems()->with(['productSku.product'])->get();
        $cartItems = $this->cartService->get();
        $addresses = $request->user()->addresses()->orderBy('last_used_at','desc')->get();
        return view('cart.index',['cartItems' => $cartItems, 'addresses' => $addresses]);
    }

    //添加购物车
    public function add(AddCartRequest $request)
    {
       $this->cartService->add($request->input('sku_id'),$request->input('amount'));
        return [];
    }

    //商品移除购物车
    public function remove(ProductSku $sku, Request $request)
    {
        $this->cartService->remove($sku->id);


        return [];
    }
}
